package com.itheima.reggie.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.Mapper.SetmealMapper;
import com.itheima.reggie.Service.SetmalDishService;
import com.itheima.reggie.Service.SetmealService;
import com.itheima.reggie.Sharing.SetmalDto;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.exception.R;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmalDishService setmalDishService;
    //保存涉及到了2张表
    @Override
    public void saveWith(SetmalDto setmalDto) {

        setmealService.save(setmalDto);
        List<SetmealDish> list=setmalDto.getSetmealDishes();
        Long loId=setmalDto.getId();
        for (SetmealDish setmealDish:list)
        {
            setmealDish.setSetmeal_id(loId);
        }

        setmalDishService.saveBatch(list);
    }

    //删除
    @Override
    public void DeleWith(List<Long> ids) {
        //select count(*) from setmeal where id in(1,2,3) and status=1   必须不是代售模式才可以删
        QueryWrapper<Setmeal> queryWrapper=new QueryWrapper<>();
        queryWrapper.in("id",ids);
        queryWrapper.eq("status",1);
        int conut=setmealService.count(queryWrapper);
        if(conut>0) {
            //如果conut>0时则删除失败抛出一个异常,
            throw  new CustomException("套餐正在售卖中,不能删除");
        }
        //如果能删除,先删除套餐的数据
           setmealService.removeByIds(ids);
        //再删除关系表的数据
        QueryWrapper<SetmealDish> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("setmeal_id",ids);
        setmalDishService.remove(queryWrapper1);

    }

    //回显
    @Override
    public SetmalDto Huixian(Long id) {
        SetmalDto dto=new SetmalDto();

        //查套餐表的信息
        Setmeal setmea= setmealService.getById(id);
        //查询关联表的信息
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("setmeal_id",id);
        List<SetmealDish> list=setmalDishService.list(queryWrapper);
        BeanUtils.copyProperties(setmea,dto);
             dto.setSetmealDishes(list);
        return dto;
    }

    //更新
    @Override
    public void update2(SetmalDto dto) {
        //修改套餐表
        Long id=dto.getId();
        setmealService.updateById(dto);
        //修改关联表
       List<SetmealDish> list= dto.getSetmealDishes();
       for(SetmealDish dish:list)
       {
           dish.setSetmeal_id(id);
       }
       setmalDishService.updateBatchById(list);
    }


}
